#include "progress_bar.h"
#define COLOR_PINK "\x1B[38;2;255;105;180m"
#define COLOR_RED     "\x1B[31m"    // 红色
#define COLOR_GREEN   "\x1B[32m"    // 绿色
#define COLOR_YELLOW  "\x1B[33m"    // 黄色
#define COLOR_BLUE    "\x1B[34m"    // 蓝色
#define COLOR_MAGENTA "\x1B[35m"    // 品红/紫色 (接近粉色)
#define COLOR_CYAN    "\x1B[36m"    // 青色
#define COLOR_WHITE   "\x1B[37m"    // 白色
#define COLOR_RESET   "\x1B[0m"     // 重置颜色

// 进度条函数，控制刷新频率
void show_progress_bar(off_t current, off_t total, struct timeval *start) {
    static off_t last_shown = 0;
    static struct timeval last_time = {0};

    double perc = (double)current / total;
    int perc_int = (int)(perc * 100);

    struct timeval now;
    gettimeofday(&now, NULL);
    double elapsed_since_last = (now.tv_sec - last_time.tv_sec) + (now.tv_usec - last_time.tv_usec) / 1e6;

    // 只有进度提升1%或者过了100ms才刷新
    if (perc_int > (int)(100.0 * last_shown / total) || elapsed_since_last > 0.1 || current == total) {
        last_time = now;
        last_shown = current;

        int width = 40;
        int pos = width * perc;

        double elapsed = (now.tv_sec - start->tv_sec) + (now.tv_usec - start->tv_usec) / 1e6;
        double speed = elapsed > 0 ? (current / (1024.0 * 1024.0)) / elapsed : 0;
        double remain = speed > 0 ? (total - current) / (1024.0 * 1024.0) / speed : 0;

        printf("\r[");
        for (int i = 0; i < width; ++i) {
            if (i < pos) printf(COLOR_GREEN "=" COLOR_RESET);
            else printf(" ");
        }
        printf("] %5.1f%% | %5.2f MB/s | ETA: %4.0fs", perc * 100, speed, remain);
        fflush(stdout);
    }
}